package com.cie2.map.services;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.cie2.map.entities.Area;
import com.cie2.map.entities.GMarkers;

// TODO Move to MAP Project
/**
 * this engine is responsible to give an abstraction layer for the gmaps. 
 * It store  the marker that define an area
 */
public class AreaEngine {
	private Session session;
	
	public AreaEngine(Session session) {
		this.session = session;
	}
	
	public void storeArea(Area area, String markers) {
		parseMarkers(area, markers);
		session.persist(area);
		session.flush();
	}
	
	private void parseMarkers(Area area, String markers) {
		String[] marklet = markers.split(":");
		GMarkers gmarkers;
		for (int i = 0; i < marklet.length; i++) {
			gmarkers  = new GMarkers();
			System.out.println(marklet[i]);
			int start = marklet[i].indexOf('(');
			int end = marklet[i].indexOf(',');
			String lat = marklet[i].substring(start+1, end).trim();
			System.out.println(lat);
			gmarkers.setLat(lat);
			start = end;
			end = marklet[i].indexOf(')');
			String lng = marklet[i].substring(start+1, end).trim();
			System.out.println(lng);
			gmarkers.setLng(lng);
			gmarkers.setArea(area);
			session.persist(gmarkers);
		}
	}
	
	public Area load(Long areaId) {
		return (Area) session.load(Area.class, areaId);
	}
	
	public List getMarkers(Area area) {
		return session.createCriteria(GMarkers.class)
			.add(Restrictions.eq("area.id", area.getId()))
			.list();
	}
	
	public List getAllAreaMarkers() {
		List markerList = new ArrayList(33);
		List list = session.createCriteria(Area.class).list();
			
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Area area = (Area) iterator.next();		
			markerList.add(session.createCriteria(GMarkers.class).add(
					Restrictions.eq("area.id", area.getId())).list());			
		}
	
		return markerList;
	}
	
	public List getAllArea() {
		return session.createCriteria(Area.class).list();
	}
}
